<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输角色名称" clearable v-model="likeName">
            <el-button slot="append" icon="el-icon-search" @click="searchRole"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="addDialogVisible=true" round>添加角色</el-button>
        </el-col>
      </el-row>

      <el-table
          :data="roleList"
          border
          style="width: 100%">
        <el-table-column prop="roleId" label="角色ID" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="isDelete" label="角色状态" :formatter="statusFormatter" align="center"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="danger" @click="removeRoleById(scope.row)">删除</el-button>
            <el-button type="warning" @click="openGrantDialog(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div align="center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- =================== 新增角色对话框 ======================== -->
    <el-dialog title="新增角色" :visible.sync="addDialogVisible">
      <el-form :model="addRoleForm" ref="addRoleForm" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- =================== 角色授权对话框 ======================== -->
    <el-dialog title="角色授权" :visible.sync="grantDialogVisible" :before-close="handleClose">
      <el-tree
          :data="permissionList"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          :check-strictly="myStrict"
          highlight-current
          :default-checked-keys="defaultChecked"
          :props="defaultProps">
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="grantPermissionClose">取 消</el-button>
        <el-button type="primary" @click="doGrantPermission">确 定</el-button>
      </div>
    </el-dialog>

    <!-- =================== 修改角色对话框 ======================== -->
    <el-dialog title="修改角色" :visible.sync="updateDialogVisible">
      <el-form :model="updateRoleForm" ref="updateRoleForm" :rules="updateRules" :label-width="formLabelWidth">
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="updateRoleForm.roleId" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateRoleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="帐号状态" prop="isDelete" :label-width="formLabelWidth">
          <el-select v-model="updateRoleForm.isDelete" placeholder="请选择角色状态">
            <el-option label="正常" value="0"></el-option>
            <el-option label="已删除" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button @click="updateResetForm">重 置</el-button>
        <el-button type="primary" @click="toUpdate()">确 定</el-button>
      </div>
    </el-dialog>



  </div>


</template>

<script>
import {Message} from "element-ui";

export default {
  name: "RoleView",
  data() {
    let checkRoleName = (rule, value, callback) => {
      // 这里我们发送请求到后端
      let url = "/role/checkRoleName/" + value;
      this.$axios.get(url).then(res => {
        if (res.data.code == 200) {
          // 可以使用
          callback();
        } else {
          this.getAllRole();
          callback(new Error(res.data.message));
        }
      })
    };

    let checkRoleByNameAndId = (rule, value, callback) => {
      let params1 =this.updateRoleForm.roleId;
      let params2 = this.updateRoleForm.roleName;
      let url = "/role/checkRoleByNameAndId/" + params1 + "/" + params2;
      this.$axios.get(url).then(res => {
        if (res.data.code == 200) {
          // 可以使用
          callback();
        } else {
          this.getAllRole();
          callback(new Error(res.data.message));
        }
      })
    };
    return {
      formLabelWidth: '120px',
      isSearching: false,
      likeName: "",

      roleList: [
        {isDelete: 0},
        {isDelete: 1}
      ],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: "",
      addDialogVisible: false,      // 新增角色对话框
      // 新增角色的表单对应的数据
      addRoleForm: {
        roleName: ""
      },
      // 修改角色的表单对应的数据
      updateDialogVisible: false,
      updateRoleForm: {
        roleName: "",
        isDelete: "",
      },
      rules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在2到10之间', trigger: 'blur'},
          {validator: checkRoleName, trigger: 'blur'}
        ]
      },
      updateRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在2到10之间', trigger: 'blur'},
          {validator: checkRoleByNameAndId, trigger: 'blur'}
        ]
      },
      // 授权需要的相关数据
      roleId: "",
      grantDialogVisible: false,    // 角色授权对话框
      permissionList: [],
      defaultProps: {
        label: "name",
        children: "children"
      },
      myStrict: false,            //是否使用严格模式
      defaultChecked: []          //默认勾选中的权限
    }
  }
  ,
  methods: {
    showEditDialog(row) {
      this.updateDialogVisible = true;
      this.updateRoleForm.roleId = row.roleId;
      this.updateRoleForm.roleName = row.roleName;
      this.updateRoleForm.isDelete = row.isDelete === 0 ? '0' : '1';
    }
    ,

    toUpdate() {
      this.$refs['updateRoleForm'].validate(valid => {
        if (valid) {
          let url = "/role/updateRole";
          let params = new URLSearchParams();
          params.append("roleId", this.updateRoleForm.roleId);
          params.append("roleName", this.updateRoleForm.roleName);
          params.append("isDelete", this.updateRoleForm.isDelete);
          this.$axios.put(url, params)
              .then(res => {
                console.log(res);
                if (res.data.code === 200) {
                  Message({
                    type: 'success',
                    message: res.data.message,
                    duration: 1000
                  })
                  this.updateDialogVisible = false;
                  this. searchRole();
                } else {
                  Message({
                    type: 'error',
                    message: res.data.message,
                    duration: 1000
                  })
                }
                this.updateDialogVisible = false;
              })
        }
      })
    },

    //删除角色
    removeRoleById(row) {
      let url = "/role/deleteRole";
      let params = new URLSearchParams();
      params.append("roleId", row.roleId);
      console.log(params);
      this.$axios.put(url, params)
          .then((res) => {
            console.log(res);
            if (res.data.code === 200) {
              Message({
                type: 'success',
                message: res.data.message,
                duration: 1000
              })
              this. searchRole();
            } else {
              Message({
                type: 'error',
                message: res.data.message,
                duration: 1000
              })
            }
          });
    },

    // 角色授权 ----------------------------------------------------------------
    // 获取所有的权限---------------------------------------------
    getAllPermission() {
      let url = "/menu/getAllPermission";
      this.$axios.get(url).then((res) => {
        if (res.data.code === 200) {
          this.permissionList = res.data.data;
        }
      })
    }
    ,
    //打开授权的模态框--------------------------------
    openGrantDialog(row) {
      // 打开窗口，回显示数据，要勾选父级时不会选中所有的子级，所以需要严格模式
      this.myStrict = true;
      // 显示对话框
      this.grantDialogVisible = true;
      this.roleId = row.roleId;

      let url = "/menu/getPermissionById/" + this.roleId;
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          this.defaultChecked = res.data.data;
          //数据显示完之后不需要严格模式
          this.myStrict = false;
        }
      })
    }
    ,
    //点击叉号关闭授权模态框
    handleClose() {
      this.grantPermissionClose();
      this.$refs.tree.setCheckedKeys([]);
    }
    ,
    // 关闭授权窗口--------------------------------
    grantPermissionClose() {
      this.grantDialogVisible = false;
      this.$refs.tree.setCheckedKeys([]);
    }
    ,

    // 点击确定按钮--------------------------------
    doGrantPermission() {
      //得到全选的id
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      //得到半选的id
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      //全选和半选得id放到一个数组里
      let permissionIds = checkedKeys.concat(halfCheckedKeys);

      let url = "/menu/grantPermissionByRoleId";
      let params = new URLSearchParams;
      params.append("roleId", this.roleId);
      params.append("ids", permissionIds);
      this.$axios.put(url, params)
          .then(res => {
            if (res.data.code === 200) {
              Message({
                type: 'success',
                message: res.data.message,
                duration: 1000
              })
            } else {
              Message({
                type: 'error',
                message: res.data.message,
                duration: 1000
              })
            }
          })
      this.grantDialogVisible = false;
    }
    ,

    // 新增角色 ----------------------------------------------------------------
    addRole() {
      this.$refs['addRoleForm'].validate(valid => {
        if (valid) {
          let url = "/role/addRole";
          let params = new URLSearchParams
          params.append("roleName", this.addRoleForm.roleName);
          this.$axios.post(url, params)
              .then((res) => {
                console.log(res);
                if (res.data.code === 200) {
                  Message({
                    type: 'success',
                    message: res.data.message,
                    duration: 1000
                  })
                } else {
                  Message({
                    type: 'error',
                    message: res.data.message,
                    duration: 1000
                  })
                }
                this.addDialogVisible = false;
                this.getAllRole();
              });
        }
      })
    },

    resetForm() {
      this.$refs['addRoleForm'].resetFields();
    },

    updateResetForm() {
      this.$refs['updateRoleForm'].resetFields();
    },

    statusFormatter(row, column, cellValue) {
      if (cellValue === 0) {
        return '正常';
      } else if (cellValue === 1) {
        return '已删除';
      }
    },

    // 通用分页函数
    getRoleList(url, params) {
      this.$axios.get(url, {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          ...params
        }
      }).then((res) => {
        if (res.data.code === 200) {
          this.roleList = res.data.data.list;
          this.total = res.data.data.total;
          this.pageNum = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
        }
      })
    },

// 获取所有角色
    getAllRole() {
      let url = "/role/findRoleInfoByPage";
      this.getRoleList(url, {});
    }
    ,

// 模糊查询
    searchRole() {
      let url = "/role/findRoleInfoLikeName";
      this.getRoleList(url, {roleName: this.likeName});
      this.isSearching = true;
    },

    handleSizeChange(val) {
      this.pageSize = val;
      if (this.isSearching) {
        this.searchRole();
      } else {
        this.getAllRole();
      }
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      if (this.isSearching) {
        this.searchRole();
      } else {
        this.getAllRole();
      }
    },
  },

  mounted() {
    this.getAllRole();
    this.getAllPermission();
  }
}
</script>

<style scoped>

</style>
